package com.work.yshop.mvp.presenter;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.work.yshop.model.Article;
import com.work.yshop.mvp.contract.ArticleContract;
import com.work.yshop.mvp.model.ArticleModel;
import com.work.yshop.ui.activity.ArticleDetailActivity;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * 文章Presenter，负责View和Model之间的交互
 */
public class ArticlePresenter implements ArticleContract.Presenter {

    private static final String TAG = "ArticlePresenter";
    private WeakReference<ArticleContract.View> viewRef;
    private ArticleContract.Model model;
    private int currentTabType = ArticleContract.TAB_LATEST; // 默认显示最新标签页

    public ArticlePresenter(Context context) {
        this.model = new ArticleModel(context);
    }

    @Override
    public void attachView(ArticleContract.View view) {
        viewRef = new WeakReference<>(view);
    }

    @Override
    public void detachView() {
        if (viewRef != null) {
            viewRef.clear();
            viewRef = null;
        }
    }

    @Override
    public void loadArticles() {
        // 默认加载当前选中的标签页内容
        loadArticlesByTab(currentTabType);
    }
    
    @Override
    public void loadArticlesByTab(int tabType) {
        if (getView() == null) return;
        
        currentTabType = tabType;
        getView().showLoading();
        new LoadArticlesByTabTask(this, tabType).execute();
    }

    @Override
    public void refreshArticles() {
        // 刷新当前选中的标签页内容
        refreshArticlesByTab(currentTabType);
    }
    
    @Override
    public void refreshArticlesByTab(int tabType) {
        loadArticlesByTab(tabType);
    }

    @Override
    public void onArticleClick(Article article) {
        if (getView() == null) return;
        
        // 在实际应用中，这里可能会跳转到文章详情页
        ArticleDetailActivity.start(getView().getContext(), article.getId());
    }

    @Override
    public void publishArticle(Article article) {
        if (getView() == null) return;

        new PublishArticleTask(this, article).execute();
    }
    
    @Override
    public void searchArticles(String keyword) {
        if (getView() == null) return;
        
        getView().showLoading();
        new SearchArticlesTask(this, keyword).execute();
    }

    /**
     * 获取当前绑定的View
     */
    private ArticleContract.View getView() {
        return viewRef != null ? viewRef.get() : null;
    }

    /**
     * 处理加载文章结果
     */
    void handleLoadArticlesResult(List<Article> articles, Exception exception) {
        if (getView() == null) return;

        getView().hideLoading();

        if (exception != null) {
            getView().showError("加载文章失败: " + exception.getMessage());
        } else if (articles == null || articles.isEmpty()) {
            getView().showEmptyView();
        } else {
            getView().showArticles(articles);
        }
    }

    /**
     * 处理发布文章结果
     */
    void handlePublishResult(boolean success, Exception exception) {
        if (getView() == null) return;

        if (success) {
            getView().showPublishResult(true, "发布成功");
        } else {
            getView().showPublishResult(false, "发布失败: " + (exception != null ? exception.getMessage() : "未知错误"));
        }
    }

    /**
     * 加载文章异步任务
     */
    private static class LoadArticlesTask extends AsyncTask<Void, Void, List<Article>> {

        private WeakReference<ArticlePresenter> presenterRef;
        private Exception exception;

        LoadArticlesTask(ArticlePresenter presenter) {
            this.presenterRef = new WeakReference<>(presenter);
        }

        @Override
        protected List<Article> doInBackground(Void... voids) {
            ArticlePresenter presenter = presenterRef.get();
            if (presenter == null) return null;

            try {
                return presenter.model.getArticleList();
            } catch (Exception e) {
                exception = e;
                Log.e(TAG, "加载文章异常", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<Article> articles) {
            ArticlePresenter presenter = presenterRef.get();
            if (presenter != null) {
                presenter.handleLoadArticlesResult(articles, exception);
            }
        }
    }
    
    /**
     * 根据标签类型加载文章异步任务
     */
    private static class LoadArticlesByTabTask extends AsyncTask<Void, Void, List<Article>> {

        private WeakReference<ArticlePresenter> presenterRef;
        private int tabType;
        private Exception exception;

        LoadArticlesByTabTask(ArticlePresenter presenter, int tabType) {
            this.presenterRef = new WeakReference<>(presenter);
            this.tabType = tabType;
        }

        @Override
        protected List<Article> doInBackground(Void... voids) {
            ArticlePresenter presenter = presenterRef.get();
            if (presenter == null) return null;

            try {
                return presenter.model.getArticleListByTab(tabType);
            } catch (Exception e) {
                exception = e;
                Log.e(TAG, "加载标签页文章异常", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<Article> articles) {
            ArticlePresenter presenter = presenterRef.get();
            if (presenter != null) {
                presenter.handleLoadArticlesResult(articles, exception);
            }
        }
    }
    
    /**
     * 搜索文章异步任务
     */
    private static class SearchArticlesTask extends AsyncTask<Void, Void, List<Article>> {

        private WeakReference<ArticlePresenter> presenterRef;
        private String keyword;
        private Exception exception;

        SearchArticlesTask(ArticlePresenter presenter, String keyword) {
            this.presenterRef = new WeakReference<>(presenter);
            this.keyword = keyword;
        }

        @Override
        protected List<Article> doInBackground(Void... voids) {
            ArticlePresenter presenter = presenterRef.get();
            if (presenter == null) return null;

            try {
                return presenter.model.searchArticles(keyword);
            } catch (Exception e) {
                exception = e;
                Log.e(TAG, "搜索文章异常", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<Article> articles) {
            ArticlePresenter presenter = presenterRef.get();
            if (presenter != null) {
                presenter.handleLoadArticlesResult(articles, exception);
            }
        }
    }

    /**
     * 发布文章异步任务
     */
    private static class PublishArticleTask extends AsyncTask<Void, Void, Boolean> {

        private WeakReference<ArticlePresenter> presenterRef;
        private Article article;
        private Exception exception;

        PublishArticleTask(ArticlePresenter presenter, Article article) {
            this.presenterRef = new WeakReference<>(presenter);
            this.article = article;
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            ArticlePresenter presenter = presenterRef.get();
            if (presenter == null) return false;

            try {
                return presenter.model.saveArticle(article);
            } catch (Exception e) {
                exception = e;
                Log.e(TAG, "发布文章异常", e);
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean success) {
            ArticlePresenter presenter = presenterRef.get();
            if (presenter != null) {
                presenter.handlePublishResult(success, exception);
            }
        }
    }
} 